<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>《H5移动端开发》九宫格抽奖</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        * {
            touch-action: none;
        }

        .main {
            margin-top: 20px;
            margin-left: 2px;
            margin-right: 2px;
        }

        .lottery-grid {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
        }

        .cell {
            background-color: pink;
            flex: 1;
            height: 120px;
            margin: 2px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .active {
            background-color: orange;
        }

        .btn {
            background-color: #4ACA6D;
        }

        .started {
            background-color: gray;
        }
    </style>
</head>

<body>
    <div class="main">
        <h3>《H5移动端开发》九宫格抽奖v2</h3><br />
        <div>
            <p>
                抽奖时，Active块速度：<br />
                静止 => 开始动 => 慢慢变快 =><br />
                即将停止时速度慢下来 => 确定商品后停止 =><br />
                跳出抽中的奖品
            </p><br />
            <p>8个奖品随机选中，几率相同</p><br />
        </div>
        <div class="lottery-grid">
            <div class="cell" id="item1" data-index=1>iPhone11</div>
            <div class="cell" id="item2" data-index=2>华为Mate30</div>
            <div class="cell" id="item3" data-index=3>谢谢惠顾</div>
            <div class="cell" id="item4" data-index=8>小米手环</div>
            <div class="cell btn" id="start">开始</div>
            <div class="cell" id="item5" data-index=4>小熊抱枕</div>
            <div class="cell" id="item6" data-index=7>格力冰箱</div>
            <div class="cell" id="item7" data-index=6>电风扇</div>
            <div class="cell" id="item8" data-index=5>蓝牙音响</div>
        </div>
    </div>

    <script>
        // 初始状态选中第一个
        document.querySelector(".lottery-grid > .cell:nth-child(1)").classList.add('active')

        const speedUpAt = 4     // 从第4个开始逐渐加速
        const minMove = 30      // 最少滚动30+下
        const slowDownAt = -10  // 距离结束还剩10次滚动时逐渐减速

        // 获取本次滚动的随机次数
        let getMoveCount = function (max = 60) {
            let moveCount = Math.ceil(Math.random() * max)
            if (moveCount < minMove) {
                moveCount += minMove
            }
            return moveCount
        }

        let items = document.querySelectorAll(".lottery-grid > .cell:not(.btn)")
        // 获取排序为[顺时针滚动顺序]的元素数组
        let sortedItems = Array.from(items).sort(function (a, b) {
            let indexA = a.getAttribute("data-index")
            let indexB = b.getAttribute("data-index")
            return indexA < indexB ? -1 : 1
        })

        let moveCount = 0
        let adding = 0
        let interval = null
        let time = 600
        let started = false

        let start = document.getElementById("start")
        // 点击[开始]，开始抽奖滚动
        start.addEventListener("touchstart", function () {
            if (started) {
                return
            }
            started = true
            start.classList.add('started')

            setActiveItem(0)

            moveCount = getMoveCount(80)
            console.log(`本次将滚动次数为：${moveCount}`)

            interval = setInterval(() => {
                moving()
            }, time);
        })

        // 滚动处理
        function moving() {
            clearInterval(interval)
            let current = 0

            // stop
            if (adding > moveCount) {
                start.classList.remove('started')
                started = false
                adding = 0
                current = moveCount % items.length
                let result = `[抽中奖品] ${current+1}: ${sortedItems[current].innerText}`
                console.log(result)
                alert(result)
                return
            }

            current = adding % items.length
            setActiveItem(current)

            // 即将结束滚动时，减速
            if (adding > moveCount + slowDownAt) {
                if (time < 800)(time += 60)
                interval = setInterval(() => {
                    moving()
                }, time);
            }
            // 滚动超过指定次数后开始加速
            else if (adding > speedUpAt) {
                if (time > 180)(time -= 60)
                interval = setInterval(() => {
                    moving()
                }, time);
            }
            // 开始滚动时
            else {
                time -= 50
                interval = setInterval(() => {
                    moving()
                }, time);
            }
            adding += 1
            console.log(time)
        }

        // 设置当前选中项
        function setActiveItem(activeIndex) {
            items.forEach(item => {
                item.classList.remove('active')
            })
            sortedItems[activeIndex].classList.add('active')
        }
    </script>
</body>

</html>